package com.steadyoung.modelapp.rxretrofit.http;


import android.app.Activity;
import android.util.Log;


import com.steadyoung.modelapp.entity.api.HttpResult;
import com.trello.rxlifecycle.components.RxActivity;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/9/7.
 * Email : steadyoung@foxmail.com
 * Auth  : wayne
 * Desc  : 网络请求统一调用类
 */
public class HttpMethods {

    private static final int DEFAULT_TIMEOUT = 15;

    private Retrofit retrofit;

    private HttpService httpService;

    //构造方法私有
    private HttpMethods() {
        //手动创建一个OkHttpClient并设置超时时间
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                //打印retrofit日志
//                Log.i("RetrofitLog","retrofitBack = "+message);
                Log.d("RetrofitLog","retrofitBack = "+ message);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        builder.addInterceptor(loggingInterceptor);
        builder.addInterceptor(new TokenInterceptor());

        retrofit = new Retrofit.Builder().client(builder.build())
                //modify by zqikai 20160317 for 对http请求结果进行统一的预处理 GosnResponseBodyConvert
//                .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(ResponseConvertFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(HttpService.BASE_URL)
                .build();

        httpService = retrofit.create(HttpService.class);
    }

    /**在访问HttpMethods时创建单例*/
    private static class SingletonHolder{
        private static final HttpMethods INSTANCE = new HttpMethods();
    }

    //获取单例
    public static HttpMethods getInstance(){
        return SingletonHolder.INSTANCE;
    }

//    /**双重检查锁单例*/
//    private volatile static HttpMethods instance = null;
//
//    public static HttpMethods getInstance() {
//        // 先检查实例是否存在，如果不存在才进入下面的同步块
//        if (instance == null) {
//            // 同步块，线程安全地创建实例
//            synchronized (HttpMethods.class) {
//                // 再次检查实例是否存在，如果不存在才真正地创建实例
//                instance = new HttpMethods();
//            }
//        }
//        return instance;
//    }


    private <T> void toSubscribe(Observable<T> o, Subscriber<T> s,RxActivity rxActivity){
         o.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                 .compose(rxActivity.<T>bindToLifecycle())
                .subscribe(s);
    }

    /**
     * 用来统一处理Http的resultCode,并将HttpResult的Data部分剥离出来返回给subscriber
     *
     * @param <T>   Subscriber真正需要的数据类型，也就是Data部分的数据类型
     */
    private class HttpResultFunc<T> implements Func1<HttpResult<T>, T> {

        @Override
        public T call(HttpResult<T> httpResult) {
//            LogUtils.d("HttpResult:" + httpResult);
            if(httpResult == null) return null;
            if(httpResult.getCode() != HttpService.SUCCESS_CODE){
//                LogUtils.d("RetrofitLog","HttpResultMsg:"+httpResult.getMsg());
                throw new ApiException(httpResult.getCode(),httpResult.getMsg());
            }
            return httpResult.getData();
        }
    }


    /**
     * 注册
     * @param subscriber  由调用者传过来的观察者对象
     * @param email 邮箱
     * @param mobile 手机
     * @param loginPassword 登录密码
     */
    /*public void userRegister( String email, String mobile,
                             String loginPassword,RxActviity rxActivity,Subscriber<UserInfo> subscriber){
        Observable observable = httpService.userRegister(email, mobile, loginPassword).map(new HttpResultFunc<UserInfo>());

        toSubscribe(observable, subscriber, rxActivity);
    }*/


}
